<?PHP

//Database Information

require 'mysql_db.inc.php';

function check_not_empty($var_name){
	if (  $_POST[$var_name] == '' ){
	  echo "Neuzpildytas laukelis $var_name <br />";
	  return false;
    }
	return true;
	
}
//$var_name = 'username';
//$$var_name  // $username
function validate_email($email){
	//http://php.lt/render/Articles;aid,46
  if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email)) {
	return TRUE;
  }
  else {
	echo "Blogas mail'as: $email <br/>";
    return FALSE;
  }
} 

function validate($var_names = array('username', 'email', 'password')){
	//if ($username == '') echo "tuščias username"
	$isOK = true;
	foreach($var_names as $var_name){
	   if (! check_not_empty($var_name)) {
		   $isOK = false; 
	   }
	}
	
	return $isOK;
}


$username = $_POST['username'];
$email = $_POST['email'];
$password = md5($_POST['password']);


if (validate() && validate_email($email)) {



	$checkuser = mysql_query("SELECT username FROM Players WHERE Username='$username'");

	$username_exist = mysql_num_rows($checkuser);

	if($username_exist > 0){
		echo "Toks vardas jau yra";
		unset($username);
		include 'registration.html';
		exit();
	}


	$query = "INSERT INTO Players (username, password, email) VALUES('$username', '$password',  '$email')";
	mysql_query($query) or die(mysql_error());
	mysql_close();
	echo "Sekmingai uzsiregistravai <br/>"; 
		echo "<a href='registration.html'> Grizti atgal</a>";
}
else { 
	echo "<a href='registration.html'> I forma</a>";
	
	}

?>
